<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <!-- 2.4 注册自定义事件 -->
    <TodoHeader
      :arr='list'
      @arr='addList'
    ></TodoHeader>

    <!-- 3.2 注册默认事件 -->
    <TodoMain
      :arr="isShowArr"
      @delList='delFn'
    ></TodoMain>
    <!-- 4.2 父传子 把list数据传代子组件中-->
    <TodoFooter
      :farr='isShowArr'
      @switch='switchBtn'
      @clear='clearFn'
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

import "./styles/base.css"
import "./styles/index.css"
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data () {
    return {
      list: JSON.parse(localStorage.getItem('todolist')) || [],
      getSel: 'all'
    }
  },
  methods: {
    // 获取到要删除的数据的索引,删除数据
    delFn (index) {
      this.list.splice(index, 1)
      console.log(index);
    },
    // 2.5 把接收到的数据添加到list数组中
    addList (val) {
      let id = this.list.length === 0 ? 100 : this.list[this.list.length - 1].id + 1
      this.list.push({
        id: id,
        name: val,
        isDone: false
      })
    },
    switchBtn (str) {
      this.getSel = str
    },
    clearFn () {
      this.list = this.list.filter(obj => obj.isDone === false)
    }
  },
  computed: {
    isShowArr () {

      if (this.getSel === 'yes') {
        return this.list.filter(obj => obj.isDone === true)
      } else if (this.getSel === 'no') {
        return this.list.filter(obj => obj.isDone === false)
      } else {
        return this.list
      }
    }
  },
  watch: {
    list: {
      deep: true,
      handler () {
        localStorage.setItem('todolist', JSON.stringify(this.list))
      }
    }
  }
};
</script>